﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Tools.Ribbon;
using System.Windows.Forms;
using System.Diagnostics;
using Microsoft.Office.Interop.Excel;
using DotSpatial;
using DotSpatial.Controls;
using DotSpatial.Symbology;
using DotSpatial.Data;

namespace DotSpatialExcelAddIn
{
    public partial class addinRibbon
    {
#region varable
        private IMap XLSMap;
        private IBasicMap _basicMap;
        public Map vMap;
        public int selectedSheet;
        public IMap xlsMap;
        private bool _chk = true;
#endregion

#region "Utility" 
        
        int getLayerHdl(String LyrName)
        {
            for (int i = 0; i < xlsMap.Layers.Count; i++)
            {
                if (xlsMap.Layers[i].LegendText != null)
                {
                    if (xlsMap.Layers[i].LegendText.ToLower() == LyrName.ToLower())
                    { return i; }
                }
            }
            return -1;
        } 

#endregion
        
        private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
        {

        }

        private void groupMap_DialogLauncherClick(object sender, RibbonControlEventArgs e)
        {
            MessageBox.Show("Click Map Group");
        }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        [DebuggerNonUserCode]
        private void cmdLoadMap_Click(object sender, RibbonControlEventArgs e)
        {
            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new MainForm());
            var formMain = new frmMap();
            formMain.Rb = this;
            formMain.Show();
            xlsMap = formMain.mapInterface as IMap;
            _basicMap = xlsMap;
          //  enableHydrotool(true);
        }
        public virtual IBasicMap Map
        {
            get { return _basicMap; }
            set { _basicMap = value; }
        }
        public bool enableTool 
        {
            get { return _chk; }
            set 
            { 
                _chk = value;
                enableHydrotool(_chk);
            }
        }

        public void enableHydrotool(bool chk)
        {
           //Map tool
            cmdAddLayer.Enabled = chk;
            cmdRemoveLayer.Enabled = chk;
            cmdTable.Enabled = chk;
            cmdSelection.Enabled = chk;
            cmdZoomIn.Enabled = chk;
            cmdZoomOut.Enabled = chk;
            cmdZoomExtend.Enabled = chk;
            cmdPan.Enabled = chk;
            cmdMeasure.Enabled = chk;
            cmdIdentify.Enabled = chk;
            //Search area
            cmdSelectFeature.Enabled = chk;
            cmdDrawRectangle.Enabled = chk;
            //Parameter
            cmdSelectParameter.Enabled = chk;
            cmdCUASHIWebService.Enabled = chk;
            cmbParameter.Enabled = chk;
            //Time range
            txtEndDate.Enabled = chk;
            txtStartDate.Enabled = chk;
            cmdTimeRange.Enabled = chk;
            //Search
            cmdDataSource.Enabled = chk;
            cmdSearch.Enabled = chk; 
        }

        private void cmdReloadAttribute_Click(object sender, RibbonControlEventArgs e)
        {
            
            /*
            Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
            Workbook wb = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            Worksheet ws = (Worksheet)wb.Worksheets[1];           
            excelApp.Visible = true;
            excelApp.Range["A1"].Value = "ID";
            excelApp.Range["B1"].Value = "Balance";
            excelApp.Range["A2"].Select();
            ws.Cells[2, 1] = "kasem"; 
             */
        Microsoft.Office.Interop.Excel.Application oXL;
        Microsoft.Office.Interop.Excel.Workbook oWB;
        Microsoft.Office.Interop.Excel.Worksheet oSheet;
        oXL = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); 
        oXL.Visible = true;
        oWB = (Microsoft.Office.Interop.Excel.Workbook)oXL.ActiveWorkbook;
        oSheet = (Worksheet)oWB.Worksheets[1];
        oSheet.Cells[2, 1] = "kasem";
        
        //docProps = oWB.CustomDocumentProperties;
        }

        private void cmdSynchronize_Click(object sender, RibbonControlEventArgs e)
        {

        }

        private void cmdTable_Click(object sender, RibbonControlEventArgs e)
        {
            if (_basicMap == null) return;

            //UncheckOtherButtonsButMe(cmdTable);

            Map mainMap = _basicMap as Map;

            if (mainMap != null)
            {
                foreach (ILayer layer in mainMap.GetAllLayers())
                {
                    IFeatureLayer fl = layer as IFeatureLayer;

                    if (fl == null) continue;
                    if (fl.IsSelected == false) continue;
                    fl.ShowAttributes();
                }
            }
            else
            {
                foreach (ILayer layer in _basicMap.GetLayers())
                {
                    IFeatureLayer fl = layer as IFeatureLayer;

                    if (fl == null) continue;
                    if (fl.IsSelected == false) continue;
                    fl.ShowAttributes();
                    
                }
            }
        }

        private void cmdIdentify_Click(object sender, RibbonControlEventArgs e)
        {
            if (_basicMap == null) return;
                _basicMap.FunctionMode = FunctionMode.Info;
        }

        private void cmdZoomIn_Click(object sender, RibbonControlEventArgs e)
        {
            if (_basicMap == null) return;
                _basicMap.FunctionMode = FunctionMode.ZoomIn;
        }

        private void cmdZoomOut_Click(object sender, RibbonControlEventArgs e)
        {
            if (_basicMap == null) return;
            _basicMap.FunctionMode = FunctionMode.ZoomOut;
        }

        private void cmdPan_Click(object sender, RibbonControlEventArgs e)
        {
            if (_basicMap == null) return;
            _basicMap.FunctionMode = FunctionMode.Pan;
        }

        private void cmdZoomPrevious_Click(object sender, RibbonControlEventArgs e)
        {

        }

        private void cmdSelection_Click(object sender, RibbonControlEventArgs e)
        {
            if (_basicMap == null) return;
            _basicMap.FunctionMode = FunctionMode.Select;
        }

        private void cmdMeasure_Click(object sender, RibbonControlEventArgs e)
        {
            MessageBox.Show("Pending...");  
        }

        private void cmdAddLayer_Click(object sender, RibbonControlEventArgs e)
        {
            if (_basicMap == null) return;
            _basicMap.AddLayer();
            if (_basicMap == null) return;
            Map mainMap = _basicMap as Map;
            IMapFeatureLayer Lyr = null;
 
            if (mainMap != null)
            {
                foreach (ILayer layer in mainMap.GetAllLayers())
                {
                    IFeatureLayer fl = layer as IFeatureLayer;

                    if (fl == null) continue;
                    //if (fl.IsSelected == false) continue;
                    Lyr = (IMapFeatureLayer)fl;
                }
            }
            else
            {
                foreach (ILayer layer in _basicMap.GetLayers())
                {
                    IFeatureLayer fl = layer as IFeatureLayer;

                    if (fl == null) continue;
                    Lyr = (IMapFeatureLayer)fl;
                }
            }
            if (Lyr != null) {
                Microsoft.Office.Interop.Excel.Application oXL;
                Microsoft.Office.Interop.Excel.Workbook oWB;
                Microsoft.Office.Interop.Excel.Worksheet oSheet;
                oXL = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
                oXL.Visible = true;
                oWB = (Microsoft.Office.Interop.Excel.Workbook)oXL.ActiveWorkbook;
                /*
                string ExcelSheetName="";
                for (int i = 1; i <= lastSheet;i++ )
                {
                    ExcelSheetName += oWB.Worksheets[i].name;
                }
                 */ 
                //frmSelectActiveSheet  frm1 = new frmSelectActiveSheet();
                //frm1.ShowDialog();

                int count = oWB.Worksheets.Count;
                Microsoft.Office.Interop.Excel.Worksheet addedSheet = oWB.Worksheets.Add(Type.Missing,
                        oWB.Worksheets[count], Type.Missing, Type.Missing);

                oSheet = (Worksheet)oWB.Worksheets[count+1];
                for (int i = 0; i < Lyr.DataSet.NumRows(); i++)
                {
                    IFeature Fe = Lyr.DataSet.GetFeature(i);
                    if (i == 0)
                    {
                        oSheet.Cells[1, 1] = "Fe_ID";
                        oSheet.Cells[1, 2] = "X";
                        for (int j = 0; j < Fe.DataRow.Table.Columns.Count; j++)
                        {
                            oSheet.Cells[1, j + 3] = Fe.DataRow.Table.Columns[j].ColumnName;
                        }
                    }
                    oSheet.Cells[i+2, 1] = i;
                    for (int j = 0; j < Fe.DataRow.Table.Columns.Count; j++)
                    {
                        object val = Fe.DataRow[j];
                        oSheet.Cells[i + 2, j + 3] = val.ToString();// Fe.DataRow.Table.Columns[j];
                    }
                }
                   var range = oSheet.get_Range("1:1");
                    range.Select();
                    range.AutoFilter(1,
                    Type.Missing,
                    Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlAnd,
                    Type.Missing,
                    true);
                    var rangeCol = oSheet.get_Range("B:B").ClearContents();
                    oSheet.Cells[1, 2] = "X";
                //range.Application.ActiveWindow.FreezePanes = true;
                 /* 
                    var chkCol = oSheet.Columns("B:B").Select();
                    Selection.ClearContents();
                    Range("B1").Select;
                    ActiveCell.FormulaR1C1 = "X";
                    Range("B2").Select;
                */

                //range.Select().AutoFilter(); 
                try { oSheet.Name = Lyr.LegendText; }
                catch { MessageBox.Show("Cannot change sheet name as GIS layer name: " + Lyr.LegendText);}
                MessageBox.Show("Import data to sheet(" + oSheet.Name + ") complete " + Lyr.DataSet.NumRows().ToString() + " record");  
            } 
              
        }

        private void cmdRemoveLayer_Click(object sender, RibbonControlEventArgs e)
        {
            //-----------------------------------------------------------
            // Clear Sheet
            Microsoft.Office.Interop.Excel.Application oXL;
            Microsoft.Office.Interop.Excel.Workbook oWB;
            Microsoft.Office.Interop.Excel.Worksheet oSheet;
            oXL = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
            oXL.Visible = true;
            oWB = (Microsoft.Office.Interop.Excel.Workbook)oXL.ActiveWorkbook;
            string LyrName = "";
            for (int i = 0; i < xlsMap.Layers.Count; i++)
            {
                LyrName = xlsMap.Layers[i].LegendText;
                try
                {
                    oSheet = (Worksheet)oWB.Worksheets[LyrName];
                    oSheet.Select();
                    oSheet.Delete();
                }
                catch
                {
                    MessageBox.Show("Cannot delete sheet " + LyrName);  
                }
            }
            //-----------------------------------------------------------
            // Clear Map
            xlsMap.Layers.Clear();  
        }

        private void cmdShapeSelection_Click(object sender, RibbonControlEventArgs e)
        {
            //EXCEL
            string stRange = "";
            bool firstRange = true;
            Microsoft.Office.Interop.Excel.Application oXL;
            Microsoft.Office.Interop.Excel.Workbook oWB;
            Microsoft.Office.Interop.Excel.Worksheet oSheet;
            oXL = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
            oXL.Visible = true;
            oWB = (Microsoft.Office.Interop.Excel.Workbook)oXL.ActiveWorkbook;
            //SHAPE
            Map mainMap = _basicMap as Map;
            string sheetName = "";
            string shapeName = "";
            foreach (ILayer layer in _basicMap.GetLayers())
            {
                IFeatureLayer fl = layer as IFeatureLayer;
                if (fl == null) continue;
                if (fl.IsSelected == true) shapeName = fl.LegendText ;
            }

            if (shapeName == "")
            {
                MessageBox.Show("Please select Map layer before");  return;
            }  

            bool haveSheet = false;        
            int lastSheet = oWB.Worksheets.Count;
            for (int i = 1; i <= lastSheet; i++)
            {
                sheetName = oWB.Worksheets[i].name;
                if (shapeName == sheetName) haveSheet = true;
            }
            
            if (haveSheet == false) 
            {
                MessageBox.Show("Sheet "+ shapeName +" not found"); return; 
            }
            oSheet = (Worksheet)oWB.Worksheets[shapeName];
            oSheet.Select();
            var rangeCol = oSheet.get_Range("B:B").ClearContents();
            oSheet.Cells[1, 2] = "X";

            int iLry = getLayerHdl(shapeName);
            List<IFeature> ls1 = new List<IFeature>();
            FeatureLayer fl1 = xlsMap.Layers[iLry] as FeatureLayer;
            ISelection il1 = fl1.Selection;


            try
            {
                ls1 = il1.ToFeatureList();
//                if (il1.Count > 10) MessageBox.Show("Your selection is greater than 10 record "); 
                stRange = "";
                for (int i = 0; i < il1.Count; i++)
                {
                    if (il1.Count <= 10)
                    {
                        string FId = (ls1[i].Fid + 1).ToString();
                        if (firstRange == true)
                        { stRange = FId + ":" + FId; firstRange = false; }
                        else
                        { stRange += ", " + FId + ":" + FId; }
                    }
                    oSheet.Cells[ls1[i].Fid + 1, 2] = "X";
                    //st += ls1[i].DataRow.ItemArray.GetValue(0).ToString() + " , "; //attribute 
                }
            }
            catch
            {
            }
            //Microsoft.Office.Interop.Excel.Range firstRow = Microsoft.Office.Interop.Excel.Range["10:10", "17:17", "20:20", "21:21", "7:7"];
            //oSheet.Range = firstRow;
            //Microsoft.Office.Interop.Excel.Range rng = oSheet.Rows("10:10", "17:17", "20:20", "21:21", "7:7");
            if (il1.Count <= 10)
            {
                try
                {
                    var range = oSheet.get_Range(stRange);
                    range.Select();
                }
                catch
                { 
//                    MessageBox.Show("The selected are greater than 10 record");
                }
            }
        }
        
        private void cmdSheetSelection_Click(object sender, RibbonControlEventArgs e)
        {
            //EXCEL
            Microsoft.Office.Interop.Excel.Application oXL;
            Microsoft.Office.Interop.Excel.Workbook oWB;
            Microsoft.Office.Interop.Excel.Worksheet oSheet;
            oXL = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
            oXL.Visible = true;
            oWB = (Microsoft.Office.Interop.Excel.Workbook)oXL.ActiveWorkbook;
            //SHAPE
            Map mainMap = _basicMap as Map;
            string sheetName = "";
            string shapeName = "";
            Microsoft.Office.Interop.Excel.Worksheet ActSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.ActiveSheet;
            sheetName = ActSheet.Name;
           
            foreach (ILayer layer in _basicMap.GetLayers())
            {
                IFeatureLayer fl = layer as IFeatureLayer;
                if (fl == null) continue;
                if (fl.LegendText.ToUpper() == sheetName.ToUpper())
                { 
                    shapeName = fl.LegendText;
                }
            }

            if (shapeName == "")
            {
                MessageBox.Show(sheetName + " Layer not found"); return;
            }

            bool haveSheet = false;
            int lastSheet = oWB.Worksheets.Count;
            for (int i = 1; i <= lastSheet; i++)
            {
                sheetName = oWB.Worksheets[i].name;
                if (shapeName == sheetName) haveSheet = true;
            }

            if (haveSheet == false)
            {
                MessageBox.Show("Sheet " + shapeName + " not found"); return;
            }
            int iLry = getLayerHdl(shapeName);
          
            List<int> ls1 = new List<int>();
            FeatureLayer fl1 = xlsMap.Layers[iLry] as FeatureLayer;
            ISelection il1 = fl1.Selection;
            oSheet = (Worksheet)oWB.Worksheets[shapeName];
            oSheet.Select();
            int n = 2;
            int m = 0;
            
            Microsoft.Office.Interop.Excel.Range rng = oSheet.Cells[2, 1] as Microsoft.Office.Interop.Excel.Range;
            while (rng.Value2 != null)
            {
                rng = oSheet.Cells[n, 2] as Microsoft.Office.Interop.Excel.Range; 
                if (rng.Value2 != null)
                {
                    string chk = Convert.ToString(rng.Value2);
                    if (chk.ToUpper() == "X")
                    {
                        ls1.Add(n - 2);
                        m++;
                    }
                }
                n++;
                rng = oSheet.Cells[n, 1] as Microsoft.Office.Interop.Excel.Range;
            } 
            fl1.Select(ls1);
            if (m > 0) MessageBox.Show("Selected " + m.ToString() + " record");
            xlsMap.Refresh(); 
        }

        private void cmdZoomExtend_Click(object sender, RibbonControlEventArgs e)
        {
            if (_basicMap == null) return;
            _basicMap.ZoomToMaxExtent();
            _basicMap.FunctionMode = FunctionMode.None;
        }

        private void cmbOnlineMap_TextChanged(object sender, RibbonControlEventArgs e)
        {
        }

        private Dictionary<string, string> _services;
        //private SearchLayerInformer _searchLayerInformer;

        private void cmdUnion_Click(object sender, RibbonControlEventArgs e)
        {

        }

        private void cmdIntersection_Click(object sender, RibbonControlEventArgs e)
        {
        }

        private void cmdCUASHIWebService_Click(object sender, RibbonControlEventArgs e)
        {
            //EXCEL
            Microsoft.Office.Interop.Excel.Application oXL;
            Microsoft.Office.Interop.Excel.Workbook oWB;
            Microsoft.Office.Interop.Excel.Worksheet oSheet;
            oXL = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
            oXL.Visible = true;
            oWB = (Microsoft.Office.Interop.Excel.Workbook)oXL.ActiveWorkbook;
            oSheet = (Worksheet)oWB.Worksheets[1];
            oSheet.Select();
            oSheet.Name = "GetWebServices";
            //var rangeCol = oSheet.get_Range("B:B").ClearContents();

            //
            Search3.SearchPlugin s3 = new Search3.SearchPlugin();
            MessageBox.Show(s3.HisCentralUrl);
            //s3.GetWebServices()
            var infos = s3.GetWebServices();
            string st = "";
            if (infos != null)
            {
                int i = 0;
                oSheet.Cells[i + 1, 1] = "ServiceCode";
                oSheet.Cells[i + 1, 2] = "DescriptionURL";
                oSheet.Cells[i + 1, 3] = "ServiceTitle";
                oSheet.Cells[i + 1, 4] = "EndpointURL";
                oSheet.Cells[i + 1, 5] = "Abstract";
                oSheet.Cells[i + 1, 6] = "SiteCount";
                oSheet.Cells[i + 1, 7] = "HISCentralID";
                oSheet.Cells[i + 1, 8] = "ServiceType";
                oSheet.Cells[i + 1, 9] = "NorthLatitude";
                oSheet.Cells[i + 1, 10] = "SouthLatitude";
                oSheet.Cells[i + 1, 11] = "ValueCount";
                foreach (var info in infos)
                {
                    i++;
                    oSheet.Cells[i + 1, 1] = info.ServiceCode;
                    oSheet.Cells[i + 1, 2] = info.DescriptionURL;
                    oSheet.Cells[i + 1, 3] = info.ServiceTitle;
                    oSheet.Cells[i + 1, 4] = info.EndpointURL;
                    oSheet.Cells[i + 1, 5] = info.Abstract;
                    oSheet.Cells[i + 1, 6] = info.SiteCount;
                    oSheet.Cells[i + 1, 7] = info.HISCentralID;
                    oSheet.Cells[i + 1, 8] = info.ServiceType;
                    oSheet.Cells[i + 1, 9] = info.NorthLatitude;
                    oSheet.Cells[i + 1, 10] = info.SouthLatitude;
                    oSheet.Cells[i + 1, 11] = info.ValueCount;
                    try
                    {
                        _services.Add(info.EndpointURL, info.DescriptionURL);
                    }
                    catch
                    { }
                }
            }
            //-------------------------------------
            //info.ServiceUrl,
            //info.DescriptionURL,
            //info.Title,
            //info.ServiceID
            //info.EndpointURL
            //-------------------------------------
            MessageBox.Show(st); 
        }

        private void cmdTimeRange_Click(object sender, RibbonControlEventArgs e)
        {
            frmSelectDate dt = new frmSelectDate();
            dt.Rb = this;
            dt.ShowDialog();
        }

    }
}

